import { useStore } from 'vuex'
import { computed } from 'vue'
import { save, remove } from 'assets/js/array-store'
import { FAVORITE_KEY } from 'assets/js/constant'
export default function useFavorite() {
  const store = useStore()
  const favoriteList = computed(() => store.state.favoriteList)
  const maxLen = 100
  // icon 图标
  function getFavoriteIcon(song) {
    return isFavorite(song) > -1 ? 'icon-favorite' : 'icon-not-favorite'
  }
  // 是收藏还是移除
  function toggleFavorite(song) {
    let list
    console.log(isFavorite(song))
    if (isFavorite(song) > -1) {
      // 存在 点击即移除
      list = remove(FAVORITE_KEY, compare)
      console.log('已经移除')
    } else {
      // 收藏
      console.log('已收藏')
      list = save(song, FAVORITE_KEY, compare, maxLen)
    }
    store.commit('setFavoriteList', list)

    function compare (item) {
      return item.id === song.id
    }
  }

  function isFavorite (song) {
    return favoriteList.value.findIndex((item) => {
      return item.id === song.id
    })
  }
  return {
    getFavoriteIcon,
    toggleFavorite
  }
}
